package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.media.client.ArticleFeign;
import com.heima.media.dto.ArticleDto;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AuditServiceImpl implements IAuditService {

    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    @Lazy
    private IWmNewsService wmNewsService;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IWmUserService wmUserService;
    @Autowired
    private IWmChannelService wmChannelService;
    @Autowired
    private IWmSensitiveService wmSensitiveService;

    @Override
    public void audit(Integer id) {
        WmNews wmNews = wmNewsService.getById(id);
        audit(wmNews);
    }

    @Async
    @Override
    public void audit(WmNews wmNews) {

        System.out.println(Thread.currentThread());
        //审核挂历的敏感词
        boolean isPass = checkSensitive(wmNews);
        //文本审核
        isPass = checkText(wmNews);
        if(!isPass)return;

        //图片审核
        isPass = checkImages(wmNews);
        if(!isPass)return;


        //远程调用文章微服务创建app文章
        if(System.currentTimeMillis()>=wmNews.getPublishTime().getTime()){
            Long articleId = createApArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(9);
            wmNewsService.updateById(wmNews);
        }else{
            wmNews.setStatus(8);
            wmNewsService.updateById(wmNews);
        }
    }

    private boolean checkSensitive(WmNews wmNews) {
        //获取所有的敏感词
        List<WmSensitive> list = wmSensitiveService.list();
        List<String> stringList = list.stream().map(s -> s.getSensitives()).collect(Collectors.toList());
        //构建一个大map
        SensitiveWordUtil.initMap(stringList);
        //使用matchwords方法
        String text = wmNews.getTitle();
        String content = wmNews.getContent();
        List<ContentDto> contentDtoList = JSON.parseArray(content,ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if(contentDto.getType().equals("text")){
                text += contentDto.getValue();
            }
        }
        Map<String,Integer> integerMap = SensitiveWordUtil.matchWords(text);
        if(integerMap.size() != 0){
            wmNews.setStatus(2);
            integerMap.keySet();
            String reason = String.join(",", integerMap.keySet());
            wmNews.setReason("子管理敏感词审核，原因内容包含："+reason);
            wmNewsService.updateById(wmNews);
            return false;
        }
        return true;
    }


    private Long createApArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        articleDto.setContent(wmNews.getContent());
        articleDto.setTitle(wmNews.getTitle());

        articleDto.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        articleDto.setAuthorName(wmUser.getName());
        articleDto.setChannelId(wmNews.getChannelId());

        WmChannel wmChannel = wmChannelService.getById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag(0);
        articleDto.setLabels(wmNews.getLabels());
        articleDto.setPublishTime(wmNews.getPublishTime());
        List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
        List<String> urlList = imageDtoList.stream().map(imageDto -> imageDto.getUrl()).collect(Collectors.toList());

        articleDto.setImages(String.join(",",urlList));
        ResponseResult<Long> responseResult = articleFeign.saveApArticle(articleDto);
        if(responseResult.getCode()==0){
            return responseResult.getData();
        }else {
            throw new RuntimeException("远程调用失败");
        }
    }

    private boolean checkImages(WmNews wmNews) {
        try {
            List<String> imageUrlList = new ArrayList<>();
            //图片=文章内容图片+文章封面图片
            String images = wmNews.getImages();
            List<ImageDto> imageDtoList = JSON.parseArray(images, ImageDto.class);
            for (ImageDto imageDto : imageDtoList) {
                imageUrlList.add(imageDto.getUrl());
            }

            //从文章内容中获取图片
            String content = wmNews.getContent();
            List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
            for (ContentDto contentDto : contentDtoList) {
                if (contentDto.getType().equals("image")) {
                    if(!imageUrlList.contains(contentDto.getValue())){
                        imageUrlList.add(contentDto.getValue());
                    }
                }
            }
            //获取内容图片和封面图片的url地址（去重后）
            //根据地址从minio中下载图片
            List<byte[]> imageList = new ArrayList<>();
            for (String url : imageUrlList) {
                InputStream inputStream = minIOService.download(url);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }

            //阿里云审核
            Map map = greenImageScan.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":{
                    return true;
                }
                case "review":{
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核需要人工审核，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核失败，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean checkText(WmNews wmNews) {
        //提取自媒体文章中的文本：标题+文章内容中的文字
        String text = wmNews.getTitle();
        String content = wmNews.getContent();
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("text")) {
                text += contentDto.getValue();
            }
        }

        try {
            Map map = greenTextScan.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":{
                    return true;
                }
                case "review":{
                    wmNews.setStatus(3);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核需要人工审核，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
                case "block":{
                    wmNews.setStatus(2);
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核失败，原因是："+label);
                    wmNewsService.updateById(wmNews);
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
